import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { permissionApi } from '@/services/permission-api.service'
import type {
  PermissionCheckResult,
  PermissionCacheStatistics,
  UserPermissions,
  PermissionSyncStatus
} from '@/services/permission-api.service'

/**
 * 权限状态管理Store
 * 管理用户权限、缓存状态和权限检查
 */
export const usePermissionStore = defineStore('permission', () => {
  // 状态
  const currentPermissions = ref<string[]>([])
  const permissionCache = ref<Map<string, boolean>>(new Map())
  const loading = ref(false)
  const lastUpdateTime = ref<Date | null>(null)
  const cacheStatistics = ref<PermissionCacheStatistics | null>(null)
  const syncStatus = ref<PermissionSyncStatus | null>(null)
  const userPermissionDetails = ref<UserPermissions | null>(null)

  // 计算属性
  const hasPermissions = computed(() => {
    return currentPermissions.value.length > 0
  })

  const permissionCount = computed(() => {
    return currentPermissions.value.length
  })

  const cacheHitRate = computed(() => {
    if (!cacheStatistics.value) return 0
    const total = cacheStatistics.value.totalCachedPermissions
    const active = cacheStatistics.value.activePermissions
    return total > 0 ? Math.round((active / total) * 100) : 0
  })

  const syncInProgress = computed(() => {
    return syncStatus.value?.syncStatus === 'running'
  })

  const permissionsExpired = computed(() => {
    if (!lastUpdateTime.value) return true
    const expireTime = new Date(lastUpdateTime.value.getTime() + 60 * 60 * 1000) // 1小时过期
    return new Date() > expireTime
  })

  // 方法

  /**
   * 初始化权限缓存
   */
  const initializePermissions = async (forceRefresh = false): Promise<void> => {
    if (loading.value) return

    // 如果已经有权限且未过期，不需要重新加载
    if (!forceRefresh && hasPermissions.value && !permissionsExpired.value) {
      return
    }

    try {
      loading.value = true

      // 获取当前用户权限
      const permissions = await permissionApi.getCurrentUserPermissions()
      currentPermissions.value = permissions

      // 更新缓存映射
      permissionCache.value.clear()
      permissions.forEach(permission => {
        permissionCache.value.set(permission, true)
      })

      lastUpdateTime.value = new Date()

      // 获取用户权限详情
      userPermissionDetails.value = await permissionApi.getUserPermissionDetails()

      console.log(`权限初始化完成，共加载 ${permissions.length} 个权限`)
    } catch (error) {
      console.error('权限初始化失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  /**
   * 检查权限
   */
  const checkPermission = async (permissionName: string): Promise<boolean> => {
    // 首先检查本地缓存
    if (permissionCache.value.has(permissionName)) {
      return permissionCache.value.get(permissionName)!
    }

    // 如果本地没有，调用API检查
    try {
      const isGranted = await permissionApi.checkPermission(permissionName)

      // 更新本地缓存
      permissionCache.value.set(permissionName, isGranted)

      // 如果有权限，添加到权限列表
      if (isGranted && !currentPermissions.value.includes(permissionName)) {
        currentPermissions.value.push(permissionName)
      }

      return isGranted
    } catch (error) {
      console.error(`权限检查失败: ${permissionName}`, error)
      return false
    }
  }

  /**
   * 批量检查权限
   */
  const checkPermissions = async (permissionNames: string[]): Promise<Record<string, boolean>> => {
    const results: Record<string, boolean> = {}
    const uncachedPermissions: string[] = []

    // 先从本地缓存获取
    permissionNames.forEach(permission => {
      if (permissionCache.value.has(permission)) {
        results[permission] = permissionCache.value.get(permission)!
      } else {
        uncachedPermissions.push(permission)
      }
    })

    // 对于未缓存的权限，调用API批量检查
    if (uncachedPermissions.length > 0) {
      try {
        const apiResults = await permissionApi.checkPermissions(uncachedPermissions)

        // 更新本地缓存
        Object.entries(apiResults).forEach(([permission, isGranted]) => {
          permissionCache.value.set(permission, isGranted)
          results[permission] = isGranted

          // 如果有权限，添加到权限列表
          if (isGranted && !currentPermissions.value.includes(permission)) {
            currentPermissions.value.push(permission)
          }
        })
      } catch (error) {
        console.error('批量权限检查失败:', error)
        // 对于失败的权限，默认为无权限
        uncachedPermissions.forEach(permission => {
          results[permission] = false
        })
      }
    }

    return results
  }

  /**
   * 检查是否有任意一个权限
   */
  const hasAnyPermission = async (permissions: string[]): Promise<boolean> => {
    const results = await checkPermissions(permissions)
    return Object.values(results).some(granted => granted)
  }

  /**
   * 检查是否有所有权限
   */
  const hasAllPermissions = async (permissions: string[]): Promise<boolean> => {
    const results = await checkPermissions(permissions)
    return Object.values(results).every(granted => granted)
  }

  /**
   * 刷新权限缓存
   */
  const refreshPermissions = async (): Promise<void> => {
    try {
      await permissionApi.refreshPermissionCache()

      // 清除本地缓存，重新初始化
      permissionCache.value.clear()
      currentPermissions.value = []
      userPermissionDetails.value = null

      await initializePermissions(true)
    } catch (error) {
      console.error('刷新权限缓存失败:', error)
      throw error
    }
  }

  /**
   * 清除权限缓存
   */
  const clearPermissionCache = async (): Promise<void> => {
    try {
      await permissionApi.clearUserPermissionCache()

      // 清除本地缓存
      permissionCache.value.clear()
      currentPermissions.value = []
      userPermissionDetails.value = null
      lastUpdateTime.value = null
    } catch (error) {
      console.error('清除权限缓存失败:', error)
      throw error
    }
  }

  /**
   * 预热权限缓存
   */
  const warmupPermissionCache = async (permissionNames?: string[]): Promise<void> => {
    try {
      const permissions = permissionNames || currentPermissions.value

      if (permissions.length === 0) {
        console.warn('没有权限需要预热')
        return
      }

      await permissionApi.warmupPermissionCache(['current'], permissions)
      console.log(`权限缓存预热完成，预热 ${permissions.length} 个权限`)
    } catch (error) {
      console.error('权限缓存预热失败:', error)
      throw error
    }
  }

  /**
   * 获取权限缓存统计信息
   */
  const loadCacheStatistics = async (): Promise<void> => {
    try {
      cacheStatistics.value = await permissionApi.getPermissionCacheStatistics()
    } catch (error) {
      console.error('获取权限缓存统计失败:', error)
    }
  }

  /**
   * 获取权限同步状态
   */
  const loadSyncStatus = async (): Promise<void> => {
    try {
      syncStatus.value = await permissionApi.getPermissionSyncStatus()
    } catch (error) {
      console.error('获取权限同步状态失败:', error)
    }
  }

  /**
   * 触发权限同步
   */
  const triggerPermissionSync = async (): Promise<void> => {
    try {
      await permissionApi.triggerPermissionSync()

      // 更新同步状态
      await loadSyncStatus()

      // 短暂延迟后刷新权限
      setTimeout(() => {
        refreshPermissions()
      }, 2000)
    } catch (error) {
      console.error('触发权限同步失败:', error)
      throw error
    }
  }

  /**
   * 修复权限不一致问题
   */
  const repairPermissionInconsistencies = async (): Promise<void> => {
    try {
      const result = await permissionApi.repairPermissionInconsistencies()

      console.log(`权限修复完成，修复 ${result.fixedIssues} 个问题，剩余 ${result.remainingIssues} 个问题`)

      // 重新初始化权限
      await initializePermissions(true)
    } catch (error) {
      console.error('修复权限不一致问题失败:', error)
      throw error
    }
  }

  /**
   * 检查权限是否过期
   */
  const validatePermissions = async (): Promise<boolean> => {
    try {
      const result = await permissionApi.validatePermissionConfiguration()
      return result.isValid
    } catch (error) {
      console.error('验证权限配置失败:', error)
      return false
    }
  }

  /**
   * 获取用户权限详情
   */
  const loadUserPermissionDetails = async (): Promise<void> => {
    try {
      userPermissionDetails.value = await permissionApi.getUserPermissionDetails()
    } catch (error) {
      console.error('获取用户权限详情失败:', error)
    }
  }

  /**
   * 添加权限到本地缓存
   */
  const addPermission = (permissionName: string): void => {
    if (!permissionCache.value.has(permissionName)) {
      permissionCache.value.set(permissionName, true)
    }

    if (!currentPermissions.value.includes(permissionName)) {
      currentPermissions.value.push(permissionName)
    }
  }

  /**
   * 从本地缓存移除权限
   */
  const removePermission = (permissionName: string): void => {
    permissionCache.value.delete(permissionName)

    const index = currentPermissions.value.indexOf(permissionName)
    if (index > -1) {
      currentPermissions.value.splice(index, 1)
    }
  }

  /**
   * 重置权限状态
   */
  const reset = (): void => {
    currentPermissions.value = []
    permissionCache.value.clear()
    userPermissionDetails.value = null
    cacheStatistics.value = null
    syncStatus.value = null
    lastUpdateTime.value = null
    loading.value = false
  }

  /**
   * 检查特定用户权限（管理员功能）
   */
  const checkUserPermission = async (userId: string, permissionName: string): Promise<boolean> => {
    try {
      return await permissionApi.checkUserPermission(userId, permissionName)
    } catch (error) {
      console.error(`检查用户权限失败: ${userId}, ${permissionName}`, error)
      return false
    }
  }

  /**
   * 获取特定用户权限（管理员功能）
   */
  const getUserPermissions = async (userId: string): Promise<string[]> => {
    try {
      return await permissionApi.getUserPermissions(userId)
    } catch (error) {
      console.error(`获取用户权限失败: ${userId}`, error)
      return []
    }
  }

  return {
    // 状态
    currentPermissions: readonly(currentPermissions),
    loading: readonly(loading),
    lastUpdateTime: readonly(lastUpdateTime),
    cacheStatistics: readonly(cacheStatistics),
    syncStatus: readonly(syncStatus),
    userPermissionDetails: readonly(userPermissionDetails),

    // 计算属性
    hasPermissions,
    permissionCount,
    cacheHitRate,
    syncInProgress,
    permissionsExpired,

    // 方法
    initializePermissions,
    checkPermission,
    checkPermissions,
    hasAnyPermission,
    hasAllPermissions,
    refreshPermissions,
    clearPermissionCache,
    warmupPermissionCache,
    loadCacheStatistics,
    loadSyncStatus,
    triggerPermissionSync,
    repairPermissionInconsistencies,
    validatePermissions,
    loadUserPermissionDetails,
    addPermission,
    removePermission,
    reset,
    checkUserPermission,
    getUserPermissions
  }
})

/**
 * 权限检查组合式函数
 * 提供便捷的权限检查方法
 */
export function usePermissions() {
  const permissionStore = usePermissionStore()

  /**
   * 创建权限检查方法
   */
  const createPermissionChecker = (permissionName: string) => {
    return computed(() => {
      return permissionStore.currentPermissions.includes(permissionName) ||
             permissionStore.permissionCache.has(permissionName)
    })
  }

  /**
   * 创建权限检查函数
   */
  const createPermissionCheckFunction = (permissionName: string) => {
    return async () => {
      return await permissionStore.checkPermission(permissionName)
    }
  }

  /**
   * 权限检查装饰器
   */
  const withPermissionCheck = <T extends (...args: any[]) => any>(
    fn: T,
    permissions: string | string[],
    options: {
      requireAll?: boolean
      fallback?: any
    } = {}
  ) => {
    return async (...args: Parameters<T>): Promise<ReturnType<T>> => {
      const permissionList = Array.isArray(permissions) ? permissions : [permissions]
      const { requireAll = false, fallback } = options

      let hasPermission: boolean

      if (requireAll) {
        hasPermission = await permissionStore.hasAllPermissions(permissionList)
      } else {
        hasPermission = await permissionStore.hasAnyPermission(permissionList)
      }

      if (!hasPermission) {
        if (fallback !== undefined) {
          return fallback
        }
        throw new Error(`权限不足，需要权限: ${permissionList.join(', ')}`)
      }

      return fn(...args)
    }
  }

  return {
    ...permissionStore,
    createPermissionChecker,
    createPermissionCheckFunction,
    withPermissionCheck
  }
}